<?php

class UserController extends Controller{

    private $M_users;
    private $M_cates;
    private $M_roles;
    private $M_user_has_roles;
    private $M_cate_has_users;

    /**
     * 构造方法
     * 初始化
     */
    public function __construct(){
        $this->M_users = Model::getInstance('users');
        $this->M_cates = Model::getInstance('cates');
        $this->M_roles = Model::getInstance('roles');
        $this->M_user_has_roles = Model::getInstance('user has roles');
        $this->M_cate_has_users = Model::getInstance('cate has users');
    }

    public function login(){

        $account = $this->input()->post('account');
        $password = substr(md5($this->input()->post('password').PASSWORD_PREFIX),0,16);

        $user_info = $this->M_users->loginUser($account,$password);

        if($user_info){
            $this->session()->set('user_id',$user_info['user_id']);
            setcookie('user_id', $user_info['user_id'], time()+3600*24, '/', getHttpHost(false));
            $ret = $this->M_users->loginlog($user_info['user_id']);
            redirect(SITE_URL . 'index.php');
        }else{
            $data = array(
                'message'=>'登录失败，用户名或密码错误！',
                'url'    => SITE_URL . 'login.php',
            );
            Template::show('login/error.php',$data);
        }
    }


    public function isLogin(){

        if($_COOKIE['user_id'] && $this->session()->get('user_id') == $_COOKIE['user_id']){
            return true;
        }
        return false;
    }

    public function needLogin(){
        $is_login = $this->isLogin();

        if(!$is_login){
            if($this->input()->isAjax()){
                echo '{"statusCode":"301"}';
                exit;
            }else{
                redirect('login.php');
            }
        }
        if($this->session()->get('user_id')){
            return $this->M_users->getUserById($this->session()->get('user_id'));
        }
        return array();
    }

    //是否有权限
    public function isAction($action_name,$user_id = ''){

        $is_action = $this->M_users->isAction($action_name,$user_id);

        if(!$is_action){
            echo '{"statusCode":"300","message":"对不起，您没有权限访问该页面或您访问的页面不存在"'.$action_name.'"！"}';
            exit;
        }
    }

    //模块首页
    public function index(){
        global $controller;

        $curr_page = (int)$this->input()->post('pageNum',1);
        $per_page  = (int)$this->input()->post('numPerPage',30);
        $account = $this->input()->post('account');

        $filter = array();

        if($account){
            $filter['account'] = $account;
        }

        $user_list = $this->M_users->getUserList($curr_page,$per_page,$filter);

        $data = array(
            'controller'=>$controller,
            'user_list'=>$user_list,
        );
        Template::show('user/index.php',$data);
    }
    public function add(){
        global $controller;

        $data = array(
            'controller'=>$controller,
        );

        Template::show('user/add.php',$data);
    }

    public function delUser(){
        $user_id = $this->input()->get('user_id');
        $ret = $this->M_users->delUser($user_id);

        if($ret){
            $this->M_cate_has_users->delByUserId($user_id);
            $this->M_user_has_roles->delByUserId($user_id);
            $data = array(
                "statusCode"=>"200",
                "navTabId"=>"user",
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"删除失败",
            );
            echo Response::JSON(300,$data);
        }
        exit;
    }

    public function edit(){
        global $controller;

        $user_id = (int)$this->input()->get('user_id');

        $editrole = (int)$this->input()->get('editrole',1);

        $user_info = $this->M_users->getUserById($user_id);

        $roles = $this->M_users->getUserRoles($user_id);

        $_role_ids = $_role_names = array();

        foreach($roles as $v){
            $_role_ids[] = $v['role_id'];
            $_role_names[] = $v['role_name'];
        }

        $is_super_admin = $this->M_users->isSuperAdmin($this->session()->get('user_id'));

        $data = array(
            'controller'=>$controller,
            'role_ids'=>implode(',',$_role_ids),
            'role_names'=>implode(',',$_role_names),
            'user_info'=>$user_info,
            'editrole'=>$editrole,
            'is_super_admin'=>$is_super_admin
        );

        Template::show('user/edit.php',$data);
    }


    public function editRole(){
        global $controller;

        $user_id = (int)$this->input()->get('user_id');

        $cates = $this->M_users->getUserCates($user_id);

        $cate_ids = array();
        foreach($cates as $v){
            $cate_ids[] = $v['cate_id'];
        }

        $menu_arr = $this->M_cates->getTree();

        $data = array(
            'controller'=>$controller,
            'user_id'=>$user_id,
            'menu_arr'=>$menu_arr,
            'cate_ids'=>$cate_ids,
        );

        Template::show('user/user_cate_tree.php',$data);
    }

    public function setRole(){
        global $controller;

        $user_id = (int)$this->input()->get('user_id');
        $role_name = (int)$this->input()->post('role_name');

        $filter = array();

        if($role_name){
            $filter['role_name'] = $role_name;
        }

        $roles = $this->M_roles->getRoles($filter);
        $user_roles = $this->M_users->getUserRoles($user_id);

        $role_ids = array();
        foreach($user_roles as $v){
            $role_ids[] = $v['role_id'];
        }

        $data = array(
            'controller'=>$controller,
            'user_id'=>$user_id,
            'roles'=>$roles,
            'role_ids'=>$role_ids,
        );

        Template::show('User/user_role.php',$data);
    }

    public function getUserHasRoles($user_id){
        return $this->A_roles->getUserHasRoles($user_id);
    }

    public function ajaxAdd(){
        $account = $this->input()->post('account');
        $real_name = $this->input()->post('real_name');
        $nick_name = $this->input()->post('nick_name');
        $password = $this->input()->post('password');
        $repassword = $this->input()->post('repassword');
        $email = $this->input()->post('email');

        if(!$account){
            $data = array(
                "statusCode"=>"300",
                "message"=>"必须填写用户名",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        if(!$email){
            $data = array(
                "statusCode"=>"300",
                "message"=>"必须填写联系邮箱",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        if(!$password || $password != $repassword){
            $data = array(
                "statusCode"=>"300",
                "message"=>"两次输入的密码不一致",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $tel = $this->input()->post('tel');

        $ret = $this->M_users->addUser($account,$real_name,$nick_name,$password,$email,$tel);

        $role_ids = $this->input()->post('role_ids',false);

        if($ret){

            if($role_ids){
                $role_ids = explode(',',$role_ids);
                $role_ids = array_unique($role_ids);
                foreach($role_ids as $v){
                    if($v){
                        $this->M_user_has_roles->addUserHasRoles($ret,$v);
                    }
                }
            }

            $data = array(
                "statusCode"=>"200",
                "message"=>"添加成功",
                "navTabId"=>"user",
                "callbackType"=>"closeCurrent"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"添加失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    public function ajaxEdit(){

        $user_id = $this->input()->post('user_id');
        $password = $this->input()->post('password',null);


        $user_info = $this->M_users->getUserById($user_id);

        if($password){
            $_password = substr(md5($password.PASSWORD_PREFIX),0,16);
            if( $user_info['password'] != $_password){
                $data = array(
                    "statusCode"=>"300",
                    "message"=>"请重新输入新密码",
                );
                echo Response::JSON(300,$data);
                exit;
            }
        }

        $is_super_admin = $this->M_users->isSuperAdmin($user_info['user_id']);

        if($is_super_admin){
            $data = array(
                "statusCode"=>"300",
                "message"=>"超级管理员密码不能被修改",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $newpassword = $this->input()->post('newpassword',null);
        $repassword = $this->input()->post('repassword',null);

        if($password && $newpassword != $repassword){
            $data = array(
                "statusCode"=>"300",
                "message"=>"两次输入的密码不一致",
            );
            echo Response::JSON($data);
            exit;
        }

        $account = $is_super_admin ? $this->input()->post('account') : $user_info['account'];
        $email = $this->input()->post('email');

        $tel = $this->input()->post('tel');
        $real_name = $this->input()->post('real_name');
        $nick_name = $this->input()->post('nick_name');

        $ret = $this->M_users->updateUser($user_id,$account,$real_name,$nick_name,$newpassword,$email,$tel);

        $role_ids = $this->input()->post('role_ids',false);

        if($ret){
            if($role_ids){
                $role_ids = explode(',',$role_ids);
                $role_ids = array_unique($role_ids);
                $this->M_user_has_roles->delByUserId($user_id);
                foreach($role_ids as $v){
                    if($v){
                        $this->M_user_has_roles->addUserHasRoles($user_id,$v);
                    }
                }
            }
            $data = array(
                "statusCode"=>"200",
                "message"=>"修改成功",
                "navTabId"=>"user",
                "callbackType"=>"closeCurrent"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"修改失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    public function ajaxSetUserRole(){

        $cate_ids = $this->input()->post('cate_ids');
        $user_id = $this->input()->post('user_id');

        $this->M_cate_has_users->delByUserId($user_id);

        if($cate_ids){
            $cate_ids = array_unique($cate_ids);
            foreach($cate_ids as $v){
                if($v){
                    $this->M_cate_has_users->addCateHasUsers($v,$user_id);
                }
            }
        }

        $data = array(
            "statusCode"=>"200",
            "message"=>"权限设置成功!",
            "navTabId"=>"user",
            "callbackType"=>"closeCurrent"
        );
        echo Response::JSON(200,$data);
    }

    public function ajaxUserRole(){
        $role_ids = $this->input()->post('role_ids');
        $user_id = $this->input()->post('user_id');

        if(!$role_ids){
            $data = array(
                "statusCode"=>"300",
                "message"=>"至少选择一个角色！",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $this->M_user_has_roles->delByUserId($user_id);
        if($role_ids){
            $role_ids = array_unique($role_ids);
            foreach($role_ids as $v){
                if($v){
                    $this->M_user_has_roles->addUserHasRoles($user_id,$v);
                }
            }
        }

        $data = array(
            "statusCode"=>"200",
            "message"=>"角色设置成功!",
            "navTabId"=>"user",
            "callbackType"=>"closeCurrent"
        );
        echo Response::JSON(200,$data);
    }
}